package cn.hotel.controller.common;

import cn.hotel.entity.User;
import cn.hotel.entity.Worker;
import cn.hotel.response.ResponseTool;
import cn.hotel.response.Result;
import cn.hotel.service.UserService;
import cn.hotel.service.WorkerService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;

@Slf4j
@RestController
@RequestMapping(value = "/login")
public class LoginController {
    @Resource
    private UserService userService;

    @Autowired
    private WorkerService workerService;

    @PostMapping("/admin")
    public Result adminLogin(Worker worker, HttpServletRequest request){
        log.info("admin信息{}",worker);
        String username = worker.getUsername();
        String password = worker.getPassword();
        if (username==null||password==null){
            return ResponseTool.failed("用户名或密码错误");
        }

        //判断是否为空
        Worker workInfo = workerService.queryUserByUserAndPass(username, password);
        if (workInfo ==null ){
            return ResponseTool.failed("用户名或密码错误");
        }

        //保存用户信息
        HashMap<String, Object> map = new HashMap<>();
        HttpSession session = request.getSession();
        String role = workInfo.getRole();
        Integer workerId = workInfo.getWorkerId();

        session.setAttribute("role",role);
        session.setAttribute("workerId" , workerId);

        map.put("sessionId",session.getId());
        map.put("userId",workerId);
        map.put("role",role);
        return ResponseTool.success(map);
    }


    /**
     * 普通用户登录功能，根据传入的用户信息进行登录校验
     * @param user  里面通常包含的是用户的username，password
     * @param request
     * @return
     */
    @PostMapping("/user")
    public Result userLogin(User user, HttpServletRequest request){
        log.info("user信息{}",user);
        String username = user.getUsername();
        String password = user.getPassword();
        if (username==null||password==null){
            return ResponseTool.failed("用户名或密码错误");
        }

        //判断是否为空
        User userInfo = userService.queryUserByUserAndPass(username, password);
        log.info("登录的user信息=={}",userInfo);
        if (userInfo ==null ){
            return ResponseTool.failed("用户名或密码错误");
        }

        //保存用户信息
        HashMap<String, Object> map = new HashMap<>();
        HttpSession session = request.getSession();
        session.setAttribute("userId",userInfo.getUserId());
        session.setAttribute("sessionId",session.getId());
        map.put("userId",userInfo.getUserId());
        map.put("sessionId",session.getId());
        return ResponseTool.success(map);
    }

}
